package com.chizha.iot.mqtt.simulator;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.MqttSecurityException;

import com.chizha.iot.mqtt.client.PushCallback;
import com.chizha.iot.mqtt.client.StubMQTT;

public class StableSim800Test extends StubMQTT{
	 public static final String TOPIC = "topic112";
	   private static final String clientid = "StubMQTT112";
	public static void main(String[] args) {
		StubMQTT stub = new StableSim800Test();
		stub.start();
		return;
	}

	String genReportJson() {
		return "";
	}

	protected long counter = 0;

	@Override
	public void run() {
		initialize(new PushCallbackMe(),clientid);
		message = new MqttMessage();
		message.setQos(1);
		message.setRetained(false);
		//String payload = String.format("%d", counter++);
		String payload = "A129FB112111.msgup";
		message.setPayload(payload.getBytes());

		try {
			connect();
			subscribeTopic(TOPIC, 1);
		} catch (MqttSecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("MQTT Stub Quit.");
			return;
		} catch (MqttException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("MQTT Stub Quit.");
			return;
		}
		while (true) {

			try {
				payload = String.format("%d", counter++);
				message.setPayload(payload.getBytes());
				sendTopic(TOPIC, message);
			} catch (MqttPersistenceException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.out.println("MQTT send topic failed.");

			} catch (MqttException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.out.println("MQTT send topic failed.");
			}
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	class PushCallbackMe extends PushCallback {
		public void connectionLost(Throwable cause) {
			// 连接丢失后，一般在这里面进行重连
			System.out.println("连接断开，可以做重连" + cause.getMessage());
		}

		public void deliveryComplete(IMqttDeliveryToken token) {
			// System.out.println("deliveryComplete---------" +
			// token.isComplete());
		}

		long prevoiusBody = 0;

		public void messageArrived(String topic, MqttMessage message)
				throws Exception {
			// subscribe后得到的消息会执行到这里面
			// System.out.println("接收消息主题 : " + topic);
			// System.out.println("接收消息Qos : " + message.getQos());
			 System.out.println("接收消息内容 : " + new String(message.getPayload()));
			Long b = Long.valueOf((new String(message.getPayload())));
			if ((b - prevoiusBody) != 1)
				System.out.printf(
						"-------------%d - %d--------------------\r\n", b,
						prevoiusBody);
			prevoiusBody = b;
			if (0 == (b % 10))
				System.out.printf("reach: %d \r\n", b);
		}
	}
}
